package com.ziyun.pop.mall.system.config;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.beetl.core.GroupTemplate;
import org.beetl.ext.spring.BeetlGroupUtilConfiguration;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.ziyun.pop.mall.base.service.CorePlatformService;

@Configuration
public class MVCConf implements WebMvcConfigurer, InitializingBean {

	public static final String DEFAULT_APP_NAME = "紫云报价系统";

	/**
	 * 系统名称,可以在application.properties中配置 app.name=xxx
	 */
	// @Value("${app.name}")
	// String appName;

	// 开发用的模拟当前用户和机构
	Long useId;

	Long orgId;

	String mvcTestPath;

	@Autowired
	Environment env;

	// @Autowired
	// CoreUserService userService;

	@Autowired
	BeetlGroupUtilConfiguration beetlGroupUtilConfiguration;

	@Autowired
	HttpRequestLocal httpRequestLocal;

	@Autowired
	GroupTemplate groupTemplate;

	@Value("${imagepath}")
	String imagepath;

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new SessionInterceptor(httpRequestLocal, this)).addPathPatterns("/**")
				.excludePathPatterns("/swagger-resources/**", "/swagger-ui.html", "/v2/api-docs", "/webjars/**",
						"/css/**", "/js/**/*", "/plugins/**", "/temp.do", "/appDownload.do", "/error", "/", "/oss/**",
						"/login.do", "/user/login/login.json", "/loginApi.do", "/registerUserApi.json",
						"/swagger-ui.html", "/ureport/**", "/login", "/ureport", "/mall/**", "/goods/getSellPrice.json",
						"/static/js/mall/**", "static/html/**", "/order/aliPayCallback", "/order/weixinpayCallback",
						"/order/unionPayCallback", "/order/umfPayRecall", "/order/orderPay/getOrderPaySucess",
						"/order/orderPay/postOrderPaySucess", "/user/userAdvance/index.do",
						"/user/userAdvance/postIndex.do", "/toMallIndex.do", "/quote/quotePrice.do",
						"/quote/quoteProvider.html", "/quote/findFactory.json","/registerUserPOP.json",
						"/user/userMessage/unMessageCount.json","/cart/getCartCount.json","/index.do",
						"/user/userFeedback/index.do","/exitSystem","/login/erp.html","/logout","/mallLogout","/error/notFound.do");
		registry.addInterceptor(new HandlerInterceptor() {
			@Override
			public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
					throws Exception {
				httpRequestLocal.set(request);
				return HandlerInterceptor.super.preHandle(request, response, handler);
			}
		}).addPathPatterns("/**");
		WebMvcConfigurer.super.addInterceptors(registry);
	}

	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**");
	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/static/**").addResourceLocations("classpath:/META-INF/resources/")
				.setCachePeriod(0);
	}
	
	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/").setViewName("forward:/index.do");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
		WebMvcConfigurer.super.addViewControllers(registry);
	}

	@Override
	public void addFormatters(FormatterRegistry registry) {
		registry.addFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss"));
		registry.addFormatter(new DateFormatter("yyyy-MM-dd"));
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		this.useId = env.getProperty("user.id", Long.class);
		this.orgId = env.getProperty("user.orgId", Long.class);
		this.mvcTestPath = env.getProperty("mvc.test.path");
		Map<String, Object> var = new HashMap<>(5);
		String appName = env.getProperty("app.name");
		if (appName == null) {
			var.put("appName", DEFAULT_APP_NAME);

		}

		var.put("jsVer", System.currentTimeMillis());
		var.put("imagepath",imagepath);

		groupTemplate.setSharedVars(var);

	}

}

class SessionInterceptor implements HandlerInterceptor {

	MVCConf conf;
	HttpRequestLocal httpRequestLocal;

	public SessionInterceptor(HttpRequestLocal httpRequestLocal, MVCConf conf) {
		this.conf = conf;
		this.httpRequestLocal = httpRequestLocal;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// if (conf.useId != null && conf.orgId != null
		// && request.getSession().getAttribute(CorePlatformService.ACCESS_CURRENT_USER)
		// == null) {
		// // 模拟用户登录，用于快速开发,未来用rember么代替？
		// CoreUser user = conf.userService.getUserById(conf.useId);
		// CoreOrg org = conf.userService.getOrgById(conf.orgId);
		// List<CoreOrg> orgs = conf.userService.getUserOrg(conf.useId, org.getId());
		// request.getSession().setAttribute(CorePlatformService.ACCESS_CURRENT_USER,
		// user);
		// request.getSession().setAttribute(CorePlatformService.ACCESS_CURRENT_ORG,
		// org);
		// request.getSession().setAttribute(CorePlatformService.ACCESS_USER_ORGS,
		// orgs);
		// request.getSession().setAttribute("ip", request.getRemoteHost());
		// }


		String url = request.getRequestURI();
		HttpSession session = request.getSession();
		String referer = request.getHeader("Referer");
		Object attribute = session.getAttribute(CorePlatformService.ACCESS_CURRENT_USER);
		if (session.getAttribute(CorePlatformService.ACCESS_CURRENT_USER) == null) {
			// 获得当前请求的路径
			String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
					+ request.getContextPath();
			if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
				// 是ajax请求 并且没登录 则返回403到ajax去跳转
				session.setAttribute("referer", referer);
				response.setStatus(HttpServletResponse.SC_FORBIDDEN);

			} else if (url.endsWith("/backIndex.do")) { // 如果是点击后台backStage
				response.sendRedirect("/login");
			} else {
				if (null == referer) {
					referer = url;
				}
				session.setAttribute("referer", referer);
				response.sendRedirect("/login");
			}

			return false;
		}
		return true;
	}

}
